import { useEffect, useState } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { getAuthMenuListApi } from '@/api/login';
import { isUserLoggedIn } from '@/store/user';
import Loading from '@/components/common/Loading';
import LayoutProvider from '@/components/layout/LayoutProvider';
import { useDispatch, useSelector } from 'react-redux';
import { toggleTheme } from '@/store/theme';
import { setActiveTab, addTab } from '@/store/tabs';

const AppRouter = () => {
  const [menuData, setMenuData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [collapsed, setCollapsed] = useState(false);
  const dispatch = useDispatch();
  const location = useLocation();
  
  const darkTheme = useSelector(state => state.theme.darkTheme);

  // 从 Redux store 获取布局类型
  const layoutType = useSelector(state => state.theme.layoutType || 'default');

  // 递归查找需要固定在标签页的菜单项
  const findAffixTabs = (menuItems) => {
    let affixTabs = [];
    
    const traverse = (items) => {
      items.forEach(item => {
        // 检查是否有 meta.isAffix 为 true
        if (item.meta && item.meta.isAffix) {
          affixTabs.push({
            key: item.path,
            label: item.meta.title || item.title,
            closable: false,
            icon: item.meta.icon,
            name: item.name
          });
        }
        
        // 递归处理子菜单
        if (item.children && item.children.length > 0) {
          traverse(item.children);
        }
      });
    };
    
    traverse(menuItems);
    return affixTabs;
  };

  useEffect(() => {
    // 检查用户是否已登录
    if (isUserLoggedIn()) {
      // 用户已登录，获取菜单数据
      const fetchMenu = async () => {
        try {
          await getAuthMenuListApi().then(res => {
            setMenuData(res.data);
            
            // 查找需要固定在标签页的菜单项并添加到标签页
            const affixTabs = findAffixTabs(res.data);
            affixTabs.forEach(tab => {
              dispatch(addTab(tab));
            });
            
            // 确保首页是活动的标签页
            dispatch(setActiveTab('/home'));
            
            setLoading(false);
          });
        } catch (error) {
          console.error('获取菜单数据失败:', error);
          setLoading(false);
        }
      };

      fetchMenu();
    } else {
      // 用户未登录，直接完成加载
      setLoading(false);
    }
  }, []);

  // 当路由改变时，激活对应的标签页
  useEffect(() => {
    dispatch(setActiveTab(location.pathname));
  }, [location.pathname, dispatch]);

  if (loading) {
    return <Loading />;
  }

  // 如果用户未登录，重定向到登录页
  if (!isUserLoggedIn()) {
    return <Navigate to="/login" replace />;
  }

  return (
    <LayoutProvider
      layoutType={layoutType}
      menuData={menuData}
      darkTheme={darkTheme}
      collapsed={collapsed}
      setCollapsed={setCollapsed}
      toggleThemeAction={(position) => dispatch(toggleTheme(position))}
    />
  );
};

export default AppRouter;